package cn.enilu.guns.admin.modular.door;

import cn.enilu.guns.admin.core.base.tips.ErrorTip;
import cn.enilu.guns.admin.core.base.tips.SetDataToDeviceTip;
import cn.enilu.guns.admin.equipment.service.EntranceGuardService;
import cn.enilu.guns.admin.equipment.transform.GetDeviceDataTransform;
import cn.enilu.guns.admin.modular.thread.UserCardReadThread;
import cn.enilu.guns.bean.dto.RealTimeRecordDto;
import cn.enilu.guns.bean.entity.door.EquipmentInfo;
import cn.enilu.guns.bean.entity.door.EventType;
import cn.enilu.guns.bean.entity.door.UserCard;
import cn.enilu.guns.bean.entity.system.User;
import cn.enilu.guns.service.door.UserCardService;

import cn.enilu.guns.bean.annotion.core.BussinessLog;
import cn.enilu.guns.bean.constant.factory.PageFactory;
import cn.enilu.guns.bean.dictmap.CommonDict;
import cn.enilu.guns.admin.core.base.controller.BaseController;
import cn.enilu.guns.bean.exception.GunsException;

import cn.enilu.guns.bean.vo.query.Page;
import cn.enilu.guns.bean.vo.query.SearchFilter;


import cn.enilu.guns.service.system.UserService;
import cn.enilu.guns.service.system.impl.ConstantFactory;
import cn.enilu.guns.utils.BeanUtil;
import cn.enilu.guns.utils.Lists;
import cn.enilu.guns.utils.StringUtils;
import cn.enilu.guns.warpper.door.RealTimeRecordDtoWarpper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.Queue;

@Controller
@RequestMapping("/door/USER/CARD")
public class UserCardController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private UserCardService userCardService;
    @Autowired
    private UserService userService;
    @Autowired
    private EntranceGuardService entranceGuardService;

    private static String PREFIX = "/door/USER/CARD/";

    private Boolean flag = true;

    /**
     * 跳转到首页
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String index() {
        return PREFIX + "index.html";
    }

    /**
     * 跳转到添加页面
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add() {
        return PREFIX + "add.html";
    }

    /**
     * 跳转到修改页面
     */
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        UserCard entity = userCardService.get(id);
        model.addAttribute("item", entity);
        return PREFIX + "edit.html";
    }

    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Object list(@RequestParam(required = false) String name) {
        Page<UserCard> page = new PageFactory<UserCard>().defaultPage();
        page.addFilter("userInfo.name", SearchFilter.Operator.EQ, name);
        page.addFilter("isUnbinding", SearchFilter.Operator.EQ, "1");
        page = userCardService.queryPage(page);
        return super.packForBT(page);
    }

    /**
     * 新增人卡关系
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    @BussinessLog(value = "新增人卡关系", key = "name", dict = CommonDict.class)
    public Object add(UserCard userCard) {
        List<UserCard> userCards = userCardService.queryByCondition(userCard.getCardNo(), "1");
        if (userCards.size() > 0) {
            return new ErrorTip(300, "此卡已經綁定,請先解綁!");
        }
        userCard.setIsUnbinding(1);
        userCardService.insert(userCard);
        User user = userService.get(userCard.getUserInfo().getId());
        user.setIsOwnCard("1");
        userService.update(user);
        return SUCCESS_TIP;
    }

    /**
     * 删除人卡关系
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @BussinessLog(value = "删除人卡关系", key = "id", dict = CommonDict.class)
    public Object delete(@RequestParam Long id) {
        userCardService.delete(id);
        return SUCCESS_TIP;
    }

    /**
     * 修改人卡关系
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @BussinessLog(value = "修改人卡关系", key = "name", dict = CommonDict.class)
    public Object update(UserCard userCard) {
        userCardService.update(userCard);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/unfreeze")
    @ResponseBody
    @BussinessLog(value = "解綁", key = "name", dict = CommonDict.class)
    public Object unfreeze(@RequestParam Long id) {
        UserCard entity = userCardService.get(id);
        entity.setIsUnbinding(0);
        userCardService.update(entity);
        User user = userService.get(entity.getUserInfo().getId());
        user.setIsOwnCard("0");
        userService.update(user);

        return SUCCESS_TIP;
    }

    /**
     * 获取读卡数据
     * @return
     */
    @RequestMapping(value = "/listRealTimeRecord", method = RequestMethod.POST)
    @ResponseBody
    public Object listRealTimeRecord() {
        UserCardReadThread.resetStartTime();
        RealTimeRecordDto realTimeRecordDto = UserCardReadThread.getRealTimeRecordDto();
        if(realTimeRecordDto != null){
            SetDataToDeviceTip setDataToDeviceTip = new SetDataToDeviceTip(200, realTimeRecordDto.getCardNo() + "");
            return setDataToDeviceTip;
        }
        return null;
    }

    /**
     * 启动读卡
     * @param ipAddress
     * @return
     */
    @RequestMapping(value = "/listRealTimeRecordStart", method = RequestMethod.POST)
    @ResponseBody
    public Object listRealTimeRecordStart(@RequestParam(required = false) String ipAddress) {
        if (StringUtils.isEmpty(ipAddress)) {
            return new ErrorTip(300, "請輸入设备ip地址!");
        }
        UserCardReadThread.startRead(ipAddress);
        return new ErrorTip(200, "已开始读取数据!");
    }

    /**
     * 关闭读卡
     * @param ipAddress
     * @return
     */
    @RequestMapping(value = "/closeRead", method = RequestMethod.POST)
    @ResponseBody
    public Object closeRead(@RequestParam(required = false) String ipAddress) {
        UserCardReadThread.stopRead();
        SetDataToDeviceTip setDataToDeviceTip = new SetDataToDeviceTip(200,  "关闭读卡成功");
        return setDataToDeviceTip;
    }
}